<?php
/**
 * 后台用户管理控制器
 */
 class UserController extends AuthController{
 	
	private $model;
	public function __init(){
		$this->model = K('Users');
	}
	
	
	/**
	 * 修改用户信息
	 */
	 public function editUser(){
	 	//获得要修改的用户的UID
	 	$uid = Q('get.uid');
		if(IS_POST){
			$_POST['birthday'] = strtotime($_POST['birthday']);
			if($this->model->save(Q('post.'))){
				$this->success('修改用户信息成功');
			}
			
		}
		
		//获得当前uid的用户信息
		$userInfo = $this->model->where("uid={$uid}")->find();
		//
		$city = K('City');
		//再获得他的address字段用来处理联动地区 转为一个数组
		$address = explode(',',rtrim($userInfo['addarea'],','));
		//分类省份ID
		$this->assign('addressIds',$address);		
		//省份
		$this->assign('prov',$city->getAllProvince());
		//城市
		$this->assign('citys',$city->getProvCity($address[0]));
		//县
		$this->assign('dists',$city->getDist($address[1]));
		
		$this->assign("userInfo",$userInfo);
		
		
		$this->display();		
	 }
	
	
	/**
	 * ajax检测用户是否存在
	 */
	public function checkUserExists() {
		//得到当前注册的用户名
		if (IS_AJAX) {
			$username = Q('post.username');
			$result = $this -> model -> where("username='{$username}'") -> find();
			//如果查询结果为空那么返回true表示用户可以被注册
			//否则 返回false
			if (empty($result)) {
				$this -> ajax(array('message' => '用户可以注册', 'status' => true));
			} else {
				$this -> ajax(array('message' => '用户已经被注册请更换', 'status' => false));
			}
		}

	}
	
	
	/**
	 * 添加用户
	 */
	 public function addUser(){
	 	if(IS_POST){
	 		$_POST['birthday'] = strtotime($_POST['birthday']);
			//跳转验证两次密码
			Q('post.rpassword',Q('post.password'));
			if($this->model->addUser()){
				$this->success('添加成功');
			}else{
				$this->error($this->model->error);
			}
			
	 	}
	 	//实例化城市模型
	 	$city = K('City');
		//查询到所有的省份
	 	$this->assign('province',$city->getAllProvince());
	 	$this->display();
	 }
	 
	 
	 
	
	
	
	/**
	 * 显示所有用户列表信息
	 */
	public function index(){
		//分页
		$page = new Page($this->model->count(),10,10);
		//查询所有的前台用户名
		$this->assign('users',$this->model->order('user_money DESC')->limit($page->limit())->all());
		$this->assign('page',$page->show(2));
		$this->display();		
	}
	
	
	
	/**
	 * 锁定用户
	 */
	 public function userLock(){
	 	$uid = Q('get.uid');
		$lock = Q('get.lock');
		//锁定用户或解锁用户
		//如果$lock为1那么表示锁定用户
		if($lock==1){
			if($this->model->save(array('uid'=>$uid,'is_lock'=>1))){
				$this->success('用户锁定成功');	
			}else{
				$this->error('用户锁定失败');	
			}
		}else{
			if($this->model->update(array('uid'=>$uid,'is_lock'=>0))){
				$this->success('用户解锁成功');	
			}else{
				$this->success('用户解锁失败');
			}
		}
	 }
	
 }
